<?php


class MySQLDB
{
    private $host;
    private $port;
    private $user;
    private $pwd;
    private $dbname;
    private $charset;
    private $link;

    private static $instance;

    private function __construct($params)
    {
        $this->initParam($params);
        $this->initConnect();
    }

    private function __clone()
    {
    }

    /**
     * Create by SN on 2020/3/16 13:58
     * Des : 获取单例
     * @param $params
     * @return MySQLDB
     */
    public static function getInstance($params){
        if(!self::$instance instanceof self){
            self::$instance = new self($params);
        }
        return self::$instance;
    }

    /**
     * Create by SN on 2020/3/16 13:57
     * Des : 初始化连接参数
     * @param $params
     */
    private function initParam($params){
        $this->host = $params['host']??'127.0.0.1';
        $this->port = $params['port']??'3306';
        $this->user = $params['user']??'';
        $this->pwd = $params['pwd']??'';
        $this->dbname = $params['dbname']??'';
        $this->charset = $params['charset']??'utf8';
    }

    /**
     * Create by SN on 2020/3/16 13:57
     * Des : 连接数据库
     */
    private function initConnect(){
        $this->link = @mysqli_connect($this->host, $this->user, $this->pwd, $this->dbname);
        if (mysqli_connect_error()){
            echo '数据库连接失败'.PHP_EOL;
            echo '错误信息: '.mysqli_connect_error().PHP_EOL;
            echo '错误码: '.mysqli_connect_errno().PHP_EOL;
            exit();
        }
        mysqli_set_charset($this->link, $this->charset);
    }

    /**
     * Create by SN on 2020/3/16 13:59
     * Des : 执行数据库的增删改查
     * @param $sql
     * @return bool|mysqli_result
     */
    private function execute($sql){
        if (!$res = mysqli_query($this->link, $sql)){
            echo 'SQL语句执行失败'.PHP_EOL;
            echo '错误信息：'.mysqli_error($this->link).PHP_EOL;
            echo '错误码：'.mysqli_errno($this->link).PHP_EOL;
            echo '错误的SQL语句：'.$sql.PHP_EOL;
            exit;
        }
        return $res;
    }

    /**
     * Create by SN on 2020/3/16 14:02
     * Des : 增删改查
     * @param $sql
     * @return 成功返回true, 失败返回false
     */
    public function exec($sql){
        $key = substr($sql, 0, 6);
        if(in_array($key, array('insert', 'update', 'delete'))){
            return $this->execute($sql);
        }else{
            echo '非法访问'.PHP_EOL;
            exit;
        }
    }

    /**
     * Create by SN on 2020/3/16 14:03
     * Des : 获取自动增长的编号
     * @return int|string
     */
    public function getLastInsertId(){
        return mysqli_insert_id($this->link);
    }

}